//
//  State_BindingStudy.swift
//  NaiCha
//
//  Created by 唐安坤 on 2024/7/5.
//

import SwiftUI

struct State_BindingStudy: View {
    
    @State var totalCount: Int
    @State var typeStr: String = "鲜有评价"
    @State var backColor: Color = .blue
    init(totalCount: Int) {
        //初始化方式1
        //_totalCount = State(initialValue: totalCount)
        //初始化方式2
        self.totalCount = totalCount
    }
    var body: some View {
        
        VStack{
            Button(action: {
                self.totalCount += 1
                
            }, label: {
                HStack{
                    Text("总共好评数量: \(totalCount), \(typeStr)")
                        .font(Font.system(size: 20)).fontWeight(.bold)
                }
                    .foregroundColor(.white)
                    .padding()
                    .background(backColor)
                    .clipShape(RoundedRectangle(cornerRadius: 10))
            })
            ExtractedView(totalCount: $totalCount, typeStr: $typeStr, backColor: $backColor, title: "第一课点亮好评")
            ExtractedView(totalCount: $totalCount, typeStr: $typeStr, backColor: $backColor, title: "第二课点亮好评")
            ExtractedView(totalCount: $totalCount, typeStr: $typeStr, backColor: $backColor, title: "第三课点亮好评")
        }
    }
}

#Preview {
    State_BindingStudy.init(totalCount: 0)
}

private struct ExtractedView: View {
    @Binding var totalCount: Int
    @Binding var typeStr: String
    @Binding var backColor:Color
    @State var count: Int = 0
    @State var color:Color = .blue
    var title: String
    
    var body: some View {
        Button(action: {
            count += 1
            color = count < 3 ? .blue : .red
            
            totalCount += 1
            typeStr = totalCount < 10 ? "鲜有评价" : "好评如潮"
            backColor = totalCount < 10 ? .blue : .red
           
        }, label: {
            HStack{
                Image.init(systemName: "star.circle.fill")
                    .font(Font.system(size: 20))
                Text("\(title)\(count)")
                    .font(Font.system(size: 20)).fontWeight(.bold)
            }
            .foregroundColor(.white)
            .padding()
            .background(color)
            .clipShape(RoundedRectangle(cornerRadius: 10))
        })
    }
}
